package com.bilgeadam.hibernate.model.dal;

import java.util.List;

import org.hibernate.Session;

import com.bilgeadam.hibernate.model.entity.Employee;

/**
 * 
 * @author Bora SAYINER
 * @since Nov 16, 2014 5:21:37 PM
 * @version 1.0.0
 */
public class EmployeeDal extends AbstractDal<Long, Employee> {

	@Override
	public Employee findById(Long id) {
		Session session = getSession();
		Employee employee = (Employee) session.get(Employee.class, id);
		session.close();
		return employee;
	}

	@Override
	public List<Employee> getAll() {
		Session session = getSession();
		@SuppressWarnings("unchecked")
		List<Employee> employees = session.createCriteria(Employee.class).list();
		session.close();
		return employees;
	}

	@Override
	public boolean add(Employee e) {
		boolean result = false;
		Session session = getSession();
		session.beginTransaction();
		try {
			session.save(e);
			session.getTransaction().commit();
			session.close();
			result = true;
		} catch (Exception exception) {
			session.getTransaction().rollback();
		}
		return result;
	}

	@Override
	public boolean delete(Employee e) {
		boolean result = false;
		Session session = getSession();
		session.beginTransaction();
		try {
			session.delete(e);
			session.getTransaction().commit();
			session.close();
			result = true;
		} catch (Exception exception) {
			session.getTransaction().rollback();
		}
		return result;
	}

	@Override
	public boolean update(Employee e) {
		boolean result = false;
		Session session = getSession();
		session.beginTransaction();
		try {
			session.saveOrUpdate(e);
			session.getTransaction().commit();
			session.close();
			result = true;
		} catch (Exception exception) {
			session.getTransaction().rollback();
		}
		return result;
	}

}
